﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.Data.SqlClient;

namespace cwtrock.util
{
    class ConnectionPool
    {
        private static ConnectionPool cpool = null;
        private static Object objlock = typeof(ConnectionPool);
        private int poolSize = 100;
        private int useCount = 0;
        private ArrayList pool = null;
        private String ConnectionStr = null;

        public ConnectionPool()
        {
            ConnectionStr = Config.Default.sqlconn;
            pool = new ArrayList();

        }

        public static ConnectionPool getPool()
        {
            lock (objlock)
            {
                if (cpool == null)
                {
                    cpool = new ConnectionPool();
                }
                return cpool;
            }
        }

        public SqlConnection getConnection()
        {
            lock (pool)
            {
                SqlConnection connTemp = null;
                if (pool.Count > 0)
                {
                    connTemp = (SqlConnection)pool[0];
                    pool.RemoveAt(0);
                    if (!isUserful(connTemp))
                    {
                        useCount--;
                        connTemp = getConnection();
                    }
                }
                else
                {
                    if (useCount < poolSize)
                    {
                        try
                        {
                            SqlConnection conn = new SqlConnection(ConnectionStr);
                            conn.Open();
                            useCount++;
                            connTemp = conn;
                        }catch(Exception e){

                        }

                    }

                }
                return connTemp;
            }
        }

        public void closeConnection(SqlConnection conn)
        {
            lock (pool)
            {
                if (conn != null)
                {
                    pool.Add(conn);
                }

            }

        }

        public bool isUserful(SqlConnection con)
        {
            bool result = true;
            if (con != null)
            {
                String sql = "select 1";
                SqlCommand cmd = new SqlCommand(sql,con);
                try
                {
                    cmd.ExecuteScalar().ToString();

                }
                catch
                {
                    result = false;
                }
            }
            return result;
        }

    }
}
